package com.av.android;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;

public class RegisterActivity extends BaseActivity {

	EditText name;
	EditText surname;
	EditText username;
	EditText email;
	EditText password1;
	EditText password2;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_register);
		name = (EditText)findViewById(R.id.name);
		surname = (EditText)findViewById(R.id.surname);
		username = (EditText)findViewById(R.id.username);
		email = (EditText)findViewById(R.id.email);
		password1 = (EditText)findViewById(R.id.password1);
		password2 = (EditText)findViewById(R.id.password2);
	}

	public void register(View v){
		if(checkForm()){
			showLoading("");
			new Thread(new Runnable() {
				
				public void run() {
					// TODO Auto-generated method stub
					final String response = Utils.register(name.getText().toString(), surname.getText().toString(), username.getText().toString(),
							password1.getText().toString(), email.getText().toString());
					hideLoading();
					runOnUiThread(new Runnable() {
						
						public void run() {
							// TODO Auto-generated method stub
							System.out.println(response +"aq");
							if(response.equalsIgnoreCase("success")){

								alertWithOnClickHandler("You have been registered successfully", "Thank you",new Handler(){
									@Override
									public void handleMessage(Message msg){
										setResult(123);
										finish();
									}
								});
							}else{
								alert(response);
							}
							
						}
					});
				
				}
			}).start();
		}else{
			alert("Fill all the fields with valid email and make sure your passwords match!");
		}
	}

	private boolean checkForm() {
		
		return name.getText().toString().length()!=0
				&& surname.getText().toString().length()!=0
				&& email.getText().toString().length()!=0
				&& password1.getText().toString().length()!=0
				&& password2.getText().toString().length()!=0
				&& username.getText().toString().length()!=0 
				&& password1.getText().toString().equals(password2.getText().toString())
				&& checkEmail(email.getText().toString());
	}
	public static boolean checkEmail(String email){
		int atPosition;
		atPosition=email.indexOf('@');
		if(atPosition==-1)
			return false;
		int nt;
		nt=email.lastIndexOf('.');
		if(nt<atPosition)
			return false;
		if(nt==email.length()-1)
			return false;
		return true;
	}

}
